let userListModule = (function () {
    let $deleteAll = $('.deleteAll'),
        $selectBox = $('.selectBox'),
        $searchInp = $('.searchInp'),
        $tableBox = $('.tableBox'),
        $tbody = $tableBox.find('tbody'),
        $checkList = null,
        $checkAll = $('#checkAll');


    // 绑定部门信息
    async function bindDepart() {
        let result = await queryDepart();
        if (result.code == 0) {
            let str = ``;
            result.data.forEach(item => {
                str += `	<option value="${item.id}">${item.name}</option>`;
            });
            $selectBox.append(str);
        }
    }
    // 从服务器获取员工列表进行绑定
    async function bindHTML() {
        let params = {
            departmentId: $searchInp.val(),
            search: $searchInp.val().trim()
        };
        let result = await axios.get(`/user/list?departmentId=${$selectBox.val()}&search=${$searchInp.val().trim()}`);
        // console.log(result.code);
        if (result.code != 0) return;
        let str = ``;
        result.data.forEach(item => {
            let {
                id,
                name,
                sex,
                email,
                phone,
                department,
                job,
                desc
            } = item;
            str += `<tr>
            <td class="w3"><input type="checkbox" userId='${id}' ></td>
            <td class="w10">${name}</td>
            <td class="w5">${sex==0?'男':'女'}</td>
            <td class="w10">${department}</td>
            <td class="w10">${job}</td>
            <td class="w15">${email}/td>
            <td class="w15">${phone}</td>
            <td class="w20">${desc}</td>
            <td class="w12" userId='${id}' username='${name}'>
                <a href="javascript:;">编辑</a>
                <a href="javascript:;">删除</a>
                <a href="javascript:;">重置密码</a>
            </td>
        </tr> `;
        });
        $tbody.html(str);
        $checkList = $tbody.find('input[type="checkbox"]');
    }

    function searchHandle() {
        $selectBox.change(bindHTML);
        $searchInp.on("keydown", ev => {
            if (ev.keyCode === 13) {
                bindHTML();
            }
        });
    }
    //  基于事件委托实现需求
    function delegate() {
        $tbody.click(async ev => {
            let target = ev.target,
                $target = $(target),
                TAG = target.tagName,
                TEXT = target.innerHTML.trim();
            if (TAG === 'A') {
                let userId = $target.parent().attr('userId');
                if (TEXT === "编辑") {
                    // 跳转到新增页面   为了区分是修改还是新增  需要问号传递标识  useradd.html?id
                    window.location.href = `useradd.html?id=${userId}`;
                    return;
                }
                if (TEXT === "删除") {
                    // 防止误操作  添加确认提示
                    let username = $target.parent().attr('username');
                    let flag = confirm(`确认删除${username}的信息吗？ 删除后不可恢复！`);
                    if (flag) {
                        let result = await axios.get('/user/delete', {
                            params: {
                                userId
                            }
                        });
                        if (result.code == 0) {
                            $target.parent().params().remove();
                            alert('信息删除成功！');
                            $checkList = $tbody.find('input[type="checkbox"]');
                            return;
                        }
                        alert('信息删除失败请稍后再试');
                    }
                    return;
                }
                if (TEXT === "重置密码") {
                    let username = $target.parent().attr('username');
                    let flag = confirm(`确认重置${username}的密码吗？`);
                    if (flag) {
                        let result = await axios.post('/user/resetpassword', {
                            userId
                        });
                        if (result.code == 0) {
                            alert('密码已重置');
                            return;
                        }
                        alert('信息删除失败请稍后再试');
                    }
                    return;
                }
            }
        });
    }

    // 全选处理
    function selectHandle() {
        $checkAll.click(ev => {
            let checked = $checkAll.prop('checked');
            $checkList.prop('checked', checked);
        });
        $tbody.click(ev => {
            let target = ev.target,
                TAG = target.tagName;
                if (TAG === "INPUT") {
                    let flag = true;
                    [].forEach.call($checkList, item => {
                        $(item).prop('checked') ? null : flag = false;
                    });
                    $checkAll.prop('checked', flag);
                }
        });
        $deleteAll.click(ev => {
            // 获取当前所有的选中员工
            let arr = [];
            [].forEach.call($checkList, item => {
                if ($(item).prop('checked')) {
                    arr.push($(item).attr('userId'));
                }
            });
            // 如果没有被选中
            if (arr.length === 0) {
                alert('当前没有选中项');
                return;
            }
            // 删除提示
            let flag = confirm(`确认删除${arr.length}条数据吗？`);
            if (flag) {
                let index = -1;
                let complete=()=>{
                    if(index>=arr.length){
                        alert('已删除选中项');
                    }else{
                        alert(`已删除${index+1}条数据，剩余信息无法删除  请重试联系管理员`)
                    }
                    bindHTML();
                }
                let send = async () => {
                    if (index >= arr.length) {
                        complete();
                        return;
                    };
                    let userId = arr[++index];
                    let result = await axios.get('/user/delete', {
                        params: {
                            userId
                        }
                    });
                    if (result.code != 0) {
                        // 删除中遇到错误的结束删除
                        complete();
                        return;
                    }
                    send();
                }
                send();
            }
            return;
        });
    }
    return {
        init() {
            bindDepart();
            bindHTML();
            searchHandle();
            delegate();
            selectHandle();

        }
    }
})();
userListModule.init();